#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time    : 2022/3/14 6:51 下午
# @Author  : WangZhixing


'''
输入：
图的edge
groundtruth
'''

import csv
import os
import sys
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)
import argparse
import warnings
from torch_geometric.transforms import NormalizeFeatures
from ProcessData import DependenceGraph
warnings.filterwarnings("ignore")
import matplotlib.pyplot as plt
import networkx as nx
from torch_geometric.utils.convert import to_networkx


def only_edge_anylize(edge_path:str,ground_path:str,out_path):
    G = nx.Graph()
    cluster_dict={}
    node_pos={}
    node_label={}
    node_path_length={}
    posnode_path_length = {}
    negnode_path_length={}
    with open(ground_path,"r") as gr:
        for line in gr.readlines():
            line = line.split("\n")[0]
            line = line.split()
            if "contain" in line:
                cluster = line[1]
                node = line[2]
                node_label[node]=cluster
                if cluster in cluster_dict:
                    cluster_dict[cluster].append(node)
                else:
                    tmp=[]
                    tmp.append(node)
                    cluster_dict[cluster]=tmp

    with open(edge_path,"r") as edge_fp:
        lines = edge_fp.readlines()
        for line in lines:
            x = line.split()
            if len(x) == 3:
                source = x[1]
                target = x[2]

            else:
                source = x[0]
                target = x[1]
            G.add_edge(source, target)
    H = G.to_undirected()

    for node in H.nodes:
        if node in node_label:
            label = node_label[node]
            node_set = cluster_dict[label]
            for node2 in node_set:
                if node2 != node:
                    if node in node_pos:
                        node_pos[node].append(node2)
                    else:
                        tmp = []
                        tmp.append(node2)
                        node_pos[node] = tmp


        if node not in node_pos:
            node_pos[node] = None

    # node_path_length={} //节点：平均距离，平均的节点数目
    # posnode_path_length={}//节点：pos平均距离，平均的pos节点数目
    # negnode_path_length//节点：neg平均距离，平均的neg节点数目

    for source in node_pos:
        shortest_path_length = nx.shortest_path_length(H, source=source)
        targetaverage = 0
        targetnum = 0

        posaverage = 0
        posnum = 0

        negaverage = 0
        negnum = 0
        for target in shortest_path_length.keys():
            if target != source:
                targetaverage += shortest_path_length[target]
                targetnum += 1
                if node_pos[source]!=None and target in node_pos[source]:
                    posaverage += shortest_path_length[target]
                    posnum += 1
                else:
                    negaverage += shortest_path_length[target]
                    negnum += 1

        if targetnum != 0:
            sto=[]
            sto.append(targetaverage/targetnum)
            sto.append(targetnum)
            node_path_length[source] = sto

        else:
            sto=[]
            sto.append(0)
            sto.append(0)
            node_path_length[source] = sto

        if negnum != 0:
            sto = []
            sto.append(negaverage/negnum)
            sto.append(negnum)
            negnode_path_length[source] = sto
        else:
            sto = []
            sto.append(0)
            sto.append(0)
            negnode_path_length[source] = sto

        if posnum != 0:
            sto = []
            sto.append(posaverage/posnum)
            sto.append(posnum)
            posnode_path_length[source] =sto
        else:
            sto = []
            sto.append(0)
            sto.append(0)
            posnode_path_length[source] = sto
    # 要在这里记录下来每个节点到其他节点的平均距离，以及到跟自己同一类的平均距离
    with open(os.path.join(out_path,"shortest_path_pos_neg_length.csv"), 'w', newline='') as csvfile:
        writer = csv.writer(csvfile, delimiter=',')
        tmp = ["节点名称","节点的平均最短路径长度","节点的平均最短流经所包含的节点个数","与之同类别的节点的最短路径长度","与之同类别的节点个数","不同类别的节点的最短路径长度","不同类别的节点的个数"]
        writer.writerow(tmp)

        for i in H.nodes():
            tmp = []
            tmp.append(i)
            # 'edu.uci.isr.archstudio4.comp.resources.IResources'
            tmp.append(node_path_length[i][0])
            tmp.append(node_path_length[i][1])
            # 'edu.uci.isr.archstudio4.comp.archipelago.activitydiagrams.editorsupport.events.ActivityDiagramsEvents'
            tmp.append(posnode_path_length[i][0])
            tmp.append(posnode_path_length[i][1])

            tmp.append(negnode_path_length[i][0])
            tmp.append(negnode_path_length[i][1])

            writer.writerow(tmp)


    with open(os.path.join(out_path,"file_property.csv"), 'w', newline='') as csvfile:  # python3下
        writer = csv.writer(csvfile, delimiter=',')
        keys = ['总节点个数', str(len(H.nodes)),"子图编号","子图节点个数","直径","平均距离"]
        writer.writerow(keys)
        keys = ['群聚系数',nx.average_clustering(H)]
        writer.writerow(keys)
        keys = ['网络传递性:', nx.transitivity(H)]
        writer.writerow(keys)
        lonenode = 0
        zituid = 0
        
        for c in nx.connected_components(H):
            sub = H.subgraph(c)
            zituid+=1
            if len(sub.nodes) == 1:
                lonenode += 1
            else:
                keys = ["","",zituid,
                        str(len(sub.nodes)),
                        str(nx.diameter(sub)),
                        str(nx.average_shortest_path_length(sub))]
                writer.writerow(keys)

        keys = ['孤立节点个数', str(lonenode)]
        writer.writerow(keys)



    with open(os.path.join(out_path,"shortest_path_length.csv"), 'w', newline='') as csvfile:
        writer = csv.writer(csvfile, delimiter=',')
        tmp = [" "]
        tmp+=H.nodes
        writer.writerow(tmp)
        length = dict(nx.all_pairs_shortest_path_length(G))

        for i in length.keys():
            tmp = []
            tmp.append(i)
            for node in H.nodes:
                if node in length.get(i):
                    tmp.append(length.get(i)[node])
                else:
                    tmp.append(0)
            writer.writerow(tmp)

    with open(os.path.join(out_path, "node.csv"), 'w', newline='') as csvfile:  # python3下
        writer = csv.writer(csvfile, delimiter=',')
        b = nx.betweenness_centrality(H)
        d = nx.degree_centrality(H)
        c = nx.closeness_centrality(H)
        dgr = nx.degree(H)
        key=["节点名称","度","中介中心度","度中心度","紧密中心度"]
        writer.writerow(key)
        for node in H.nodes:
            dgree = dgr[node]
            be = b[node]
            de = d[node]
            cl = c[node]
            key = [node , dgree,be,de,cl]
            writer.writerow(key)
